import 'package:flutter/material.dart';
import 'package:tv_friso_screen/utils/share_pre_utils.dart';
import 'package:tv_friso_screen/utils/toast_utils.dart';
import '../data_model/version_info.dart';
import '../login_page.dart';
import '../model/response_with_object.dart';
import '../net/api_address.dart';
import '../net/data_helper.dart';
import '../net/http_manager.dart';
import '../widget/update_dialog.dart';
import 'log_utils.dart';

class ResultCheckUtils {
  /* 10000 => '成功！' (唯一成功code)
  20111 => '系统服务端异常！'
  20001 => '请求参数异常！'
  20002 => string '请求路径非法！'
  20003 => string '服务端请求access_token令牌缺失！' (需要重新登陆)
  20004 => string '账号已被其他设备占用，请重新登录！' (需要重新登陆)
  20005 => string '请求方式非法！' (GET 或 POST)
  20006 => string '请求提交参数验证不通过！' ()
  20007 => string '账户状态异常！' ()
  20008 => string '账户未进行微信授权！' ()
  20009 => string '您的请求太频繁了，请稍后再试！' ()
  20888 => string '您的账户存在违规操作，无法继续访问！' ()
  20555 => string '系统维护升级中，请稍后再试！' ()
  21000 => string '门店待审核！'
  21001 => string '门店审核失败！'
  21002 => string '门店审核失败！'
  22001 => string '非门店端人员！
  20020 => string '非最新版本！'*/

  static const codeSuccess = 10000;

  //版本更新
  static const codeUpdate = 20008;

  //报错需回到登录页  //token失效
  static const codeTokenFaild = 20004;

  static checkResult(BuildContext context, int code, String msg) {
    // ignore: unnecessary_null_comparison
    if (msg != null && msg.isNotEmpty) {
      ToastUtils.showToast(msg);
    }

    //账号已被其他设备占用，请重新登录！' (需要重新登陆)
    if (code == codeTokenFaild) {
      SharePreUtils.setIsLogin(false);
    } else if (code == codeUpdate) {
      // postLoginAndUpdate(context);
      print("坐等更新--------- ");
    }
  }

  static void postLoginAndUpdate(BuildContext context) async {
    var formData = DataHelper.getBaseMap();

    //请求最新版本下载地址
    var response = await HttpManager()
        .get(ApiAddress.postLogin, query: formData, checkUpdate: false);
    ResponseWithObject<VersionInfo> data =
        ResponseWithObject.fromJson(response as Map<String, dynamic>, (j) {
      if (j != null) {
        return VersionInfo.fromJson(j);
      } else {
        return j;
      }
    });
    // if (data.code == HttpManager.codeSuccess) {
    // ignore: use_build_context_synchronously
    UpdateDialog(VersionInfo(data.data.newVersion, data.data.apkUrl,
            data.data.upgradeTips, data.data.size))
        .showUpdateDialog(context);
    // }
  }

  static void goLoginPage(BuildContext context) async {
    Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => const LoginPage()),
        (route) => false);
  }
}
